// 模拟聊天数据存储和管理
class ChatStorage {
  constructor() {
    this.initializeStorage();
  }

  initializeStorage() {
    if (!localStorage.getItem('chat_messages')) {
      // 初始化测试消息
      const initialMessages = [
        {
          messageId: Date.now() - 5000,
          conversationId: 1,
          senderId: 2,
          content: '您好，请问需要什么帮助？',
          sentAt: new Date(Date.now() - 3600000).toISOString()
        },
        {
          messageId: Date.now() - 4000,
          conversationId: 2,
          senderId: 3,
          content: '您的快递已经到达配送站',
          sentAt: new Date(Date.now() - 7200000).toISOString()
        },
        {
          messageId: Date.now() - 3000,
          conversationId: 3,
          senderId: 4,
          content: '请问您的地址是在哪里？',
          sentAt: new Date(Date.now() - 1800000).toISOString()
        },
        {
          messageId: Date.now() - 2000,
          conversationId: 4,
          senderId: 5,
          content: '好的，我马上去取件',
          sentAt: new Date(Date.now() - 900000).toISOString()
        }
      ];
      localStorage.setItem('chat_messages', JSON.stringify(initialMessages));
    }

    if (!localStorage.getItem('chat_conversations')) {
      // 初始化测试对话列表
      const initialConversations = [
        {
          conversationId: 1,
          user1Id: 1,
          user2Id: 2,
          startedAt: new Date(Date.now() - 86400000).toISOString() // 1天前
        },
        {
          conversationId: 2,
          user1Id: 1,
          user2Id: 3,
          startedAt: new Date(Date.now() - 172800000).toISOString() // 2天前
        },
        {
          conversationId: 3,
          user1Id: 1,
          user2Id: 4,
          startedAt: new Date(Date.now() - 259200000).toISOString() // 3天前
        },
        {
          conversationId: 4,
          user1Id: 1,
          user2Id: 5,
          startedAt: new Date(Date.now() - 345600000).toISOString() // 4天前
        }
      ];
      localStorage.setItem('chat_conversations', JSON.stringify(initialConversations));
    }

    // 初始化已读状态
    if (!localStorage.getItem('message_read_status')) {
      localStorage.setItem('message_read_status', JSON.stringify([]));
    }
  }

  // 获取所有消息
  getAllMessages() {
    return JSON.parse(localStorage.getItem('chat_messages') || '[]');
  }

  // 获取特定对话的消息
  getConversationMessages(conversationId, options = { limit: 20, offset: 0 }) {
    const messages = this.getAllMessages()
      .filter(msg => msg.conversationId === conversationId)
      .sort((a, b) => new Date(a.sentAt) - new Date(b.sentAt)); // 修改排序顺序，从早到晚
    
    // 反转分页逻辑以保持正确的显示顺序
    const total = messages.length;
    const start = Math.max(0, total - options.offset - options.limit);
    const end = total - options.offset;
    return messages.slice(start, end);
  }

  // 添加新消息
  addMessage(message) {
    const messages = this.getAllMessages();
    const newMessage = {
      ...message,
      messageId: message.messageId || Date.now(),
      sentAt: message.sentAt || new Date().toISOString(),
      status: message.status || 'sent', // 添加消息状态
      sequence: messages.length + 1 // 添加序列号
    };
    
    // 防止重复消息
    if (!messages.some(m => m.messageId === newMessage.messageId)) {
      messages.push(newMessage);
      localStorage.setItem('chat_messages', JSON.stringify(messages));
    }
    
    return newMessage;
  }

  // 获取所有对话
  getAllConversations() {
    return JSON.parse(localStorage.getItem('chat_conversations') || '[]');
  }

  // 添加清理旧消息的方法
  cleanOldMessages(days = 30) {
    const messages = this.getAllMessages();
    const cutoff = new Date();
    cutoff.setDate(cutoff.getDate() - days);

    const filteredMessages = messages.filter(msg => 
      new Date(msg.sentAt) > cutoff
    );
    
    localStorage.setItem('chat_messages', JSON.stringify(filteredMessages));
  }

  // 获取消息的已读状态
  getReadStatus() {
    return JSON.parse(localStorage.getItem('message_read_status') || '[]');
  }

  // 将对话中的所有消息标记为已读
  markConversationAsRead(conversationId, userId) {
    const readStatus = this.getReadStatus();
    const messages = this.getConversationMessages(conversationId);
    const now = new Date().toISOString();

    // 只标记当前时间之前的消息为已读
    const unreadMessages = messages.filter(msg => {
      const msgTime = new Date(msg.sentAt);
      const currentTime = new Date();
      
      return (
        msg.senderId !== userId && // 不是自己发送的消息
        msgTime < currentTime && // 只处理当前时间之前的消息
        !readStatus.some(rs => rs.messageId === msg.messageId && rs.userId === userId) // 未被标记为已读
      );
    });

    // 添加新的已读记录
    const newReadStatus = unreadMessages.map(msg => ({
      messageId: msg.messageId,
      userId: userId,
      readAt: now
    }));

    // 保存更新后的已读状态
    localStorage.setItem('message_read_status', JSON.stringify([...readStatus, ...newReadStatus]));
    return unreadMessages.length;
  }

  // 添加新方法：检查消息是否已读
  isMessageRead(messageId, userId) {
    const readStatus = this.getReadStatus();
    const message = this.getAllMessages().find(m => m.messageId === messageId);
    
    if (!message) return false;
    
    // 检查消息时间是否在已读时间之前
    const messageTime = new Date(message.sentAt);
    const readRecord = readStatus.find(rs => rs.messageId === messageId && rs.userId === userId);
    
    if (!readRecord) return false;
    
    const readTime = new Date(readRecord.readAt);
    return messageTime <= readTime;
  }
}

export const chatStorage = new ChatStorage();
